// Axios高级功能使用示例
import { 
  videoStreamAPI, 
  collectionAPI, 
  telemetryAPI, 
  fileAPI, 
  systemAPI,
  request,
  axios 
} from './index.js';

// 1. 并发请求示例
export const concurrentRequestsExample = async () => {
  try {
    // 同时发起多个请求
    const [videoStreams, systemStatus, telemetryData] = await request.all([
      videoStreamAPI.getVideoStreams(),
      systemAPI.getSystemStatus(),
      telemetryAPI.getTelemetryData()
    ]);
    
    console.log('并发请求结果:', { videoStreams, systemStatus, telemetryData });
    return { videoStreams, systemStatus, telemetryData };
  } catch (error) {
    console.error('并发请求失败:', error);
  }
};

// 2. 带进度的并发请求
export const concurrentRequestsWithProgress = async () => {
  try {
    const requests = [
      videoStreamAPI.getVideoStreams(),
      systemAPI.getSystemStatus(),
      telemetryAPI.getTelemetryData(),
      fileAPI.getFileList()
    ];
    
    const results = await request.allSettled(requests);
    
    const successful = results.filter(result => result.status === 'fulfilled');
    const failed = results.filter(result => result.status === 'rejected');
    
    console.log(`成功: ${successful.length}, 失败: ${failed.length}`);
    
    return {
      successful: successful.map(result => result.value),
      failed: failed.map(result => result.reason)
    };
  } catch (error) {
    console.error('并发请求失败:', error);
  }
};

// 3. 请求取消示例
export const cancelableRequestExample = async () => {
  // 创建取消令牌
  const cancelToken = request.createCancelToken();
  
  try {
    // 发起一个可能耗时的请求
    const promise = videoStreamAPI.getVideoStreams();
    
    // 模拟3秒后取消请求
    setTimeout(() => {
      request.cancel(cancelToken);
      console.log('请求已取消');
    }, 3000);
    
    const result = await promise;
    console.log('请求完成:', result);
    return result;
  } catch (error) {
    if (axios.isCancel(error)) {
      console.log('请求被取消:', error.message);
    } else {
      console.error('请求失败:', error);
    }
  }
};

// 4. 文件上传进度示例
export const uploadWithProgress = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('category', 'video');
    
    const response = await axios.post('/system/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        console.log(`上传进度: ${percentCompleted}%`);
      }
    });
    
    console.log('文件上传成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('文件上传失败:', error);
  }
};

// 5. 请求重试示例
export const retryRequestExample = async (maxRetries = 3) => {
  let lastError;
  
  for (let i = 0; i < maxRetries; i++) {
    try {
      console.log(`尝试第 ${i + 1} 次请求...`);
      const result = await videoStreamAPI.getVideoStreams();
      console.log('请求成功:', result);
      return result;
    } catch (error) {
      lastError = error;
      console.log(`第 ${i + 1} 次请求失败:`, error.message);
      
      if (i < maxRetries - 1) {
        // 等待一段时间后重试
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
      }
    }
  }
  
  console.error('所有重试都失败了:', lastError);
  throw lastError;
};

// 6. 请求超时设置示例
export const timeoutRequestExample = async () => {
  try {
    // 设置5秒超时
    const response = await request.get('/system/status', {}, { timeout: 5000 });
    console.log('请求成功:', response);
    return response;
  } catch (error) {
    if (error.code === 'ECONNABORTED') {
      console.error('请求超时');
    } else {
      console.error('请求失败:', error);
    }
  }
};

// 7. 自定义请求头示例
export const customHeadersExample = async () => {
  try {
    const response = await request.get('/system/status', {}, {
      headers: {
        'X-Custom-Header': 'custom-value',
        'X-Request-ID': Date.now().toString()
      }
    });
    
    console.log('自定义请求头请求成功:', response);
    return response;
  } catch (error) {
    console.error('请求失败:', error);
  }
};

// 8. 响应拦截器示例
export const responseInterceptorExample = async () => {
  try {
    // 添加临时响应拦截器
    const interceptor = axios.interceptors.response.use(
      (response) => {
        console.log('响应拦截器:', response.data);
        return response;
      },
      (error) => {
        console.log('错误拦截器:', error);
        return Promise.reject(error);
      }
    );
    
    const response = await videoStreamAPI.getVideoStreams();
    
    // 移除拦截器
    axios.interceptors.response.eject(interceptor);
    
    return response;
  } catch (error) {
    console.error('请求失败:', error);
  }
};

// 9. 请求队列示例
export const requestQueueExample = async () => {
  const queue = [];
  const maxConcurrent = 2;
  let running = 0;
  
  const executeRequest = async (requestFn) => {
    running++;
    try {
      const result = await requestFn();
      return result;
    } finally {
      running--;
      processQueue();
    }
  };
  
  const processQueue = () => {
    while (queue.length > 0 && running < maxConcurrent) {
      const { requestFn, resolve, reject } = queue.shift();
      executeRequest(requestFn).then(resolve).catch(reject);
    }
  };
  
  const addToQueue = (requestFn) => {
    return new Promise((resolve, reject) => {
      queue.push({ requestFn, resolve, reject });
      processQueue();
    });
  };
  
  // 添加多个请求到队列
  const promises = [
    addToQueue(() => videoStreamAPI.getVideoStreams()),
    addToQueue(() => systemAPI.getSystemStatus()),
    addToQueue(() => telemetryAPI.getTelemetryData()),
    addToQueue(() => videoStreamAPI.getVideoStreams())
  ];
  
  try {
    const results = await Promise.all(promises);
    console.log('队列请求完成:', results);
    return results;
  } catch (error) {
    console.error('队列请求失败:', error);
  }
};

// 10. 缓存请求示例
export const cachedRequestExample = async () => {
  const cache = new Map();
  const cacheTimeout = 5 * 60 * 1000; // 5分钟
  
  const getCachedData = async (key, requestFn) => {
    const cached = cache.get(key);
    
    if (cached && Date.now() - cached.timestamp < cacheTimeout) {
      console.log('使用缓存数据:', key);
      return cached.data;
    }
    
    console.log('发起新请求:', key);
    const data = await requestFn();
    
    cache.set(key, {
      data,
      timestamp: Date.now()
    });
    
    return data;
  };
  
  try {
    const videoSources = await getCachedData(
      'videoSources',
      () => videoStreamAPI.getVideoStreams()
    );
    
    const systemStatus = await getCachedData(
      'systemStatus',
      () => systemAPI.getSystemStatus()
    );
    
    console.log('缓存请求结果:', { videoSources, systemStatus });
    return { videoSources, systemStatus };
  } catch (error) {
    console.error('缓存请求失败:', error);
  }
};

// 导出所有示例
export default {
  concurrentRequestsExample,
  concurrentRequestsWithProgress,
  cancelableRequestExample,
  uploadWithProgress,
  retryRequestExample,
  timeoutRequestExample,
  customHeadersExample,
  responseInterceptorExample,
  requestQueueExample,
  cachedRequestExample
}; 